package arina.university.dao.impl.memory;

import arina.university.dao.GroupDAO;
import arina.university.errorhandling.DAOException;
import arina.university.model.Group;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 26.11.13
 * Time: 15:21
 * To change this template use File | Settings | File Templates.
 */
public class MemoryGroupDAO implements GroupDAO {
    private Map<Integer,Group> groups = new HashMap<Integer,Group>();
    static private MemoryGroupDAO memoryGroupDAO;

    private MemoryGroupDAO() {
    }

    public static MemoryGroupDAO getInstance() {
        if (memoryGroupDAO == null) {
            memoryGroupDAO = new MemoryGroupDAO();
        }
        return memoryGroupDAO;

    }

    public boolean checkExistence(int id){
        if (groups.containsKey(id)) {return true;}
        else return false;
    }

    @Override
    public Group create(int id, String s) throws DAOException{
        if(checkExistence(id)) {
            throw new DAOException("Group with such id has already been created");
        }
        Group group = new Group(id,s);
        groups.put(group.getNumber(), group);
        return group;
    }

    @Override
    public void delete(int id) throws DAOException{
        if(!checkExistence(id)) {
            throw new DAOException("There is no such group");
        }
        groups.remove(id);
    }

    @Override
    public void save(Group group) throws DAOException {
        if(checkExistence(group.getNumber())){
            throw new DAOException("Group with such ID already exists");
        }

        groups.put(group.getNumber(), group);
    }

    @Override
    public Group find(int id) throws DAOException {
        if(!checkExistence(id)){
            throw new DAOException("There is no such group");
        }
        return groups.get(id);

    }

    @Override
    public Collection<Group> findAll() throws DAOException {
        if (groups.values().isEmpty()){
            throw new DAOException("You have no groups");
        }
        return groups.values();

    }
}
